package skean.yzsm.com.androidvideocache;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.WindowManager;
import android.widget.Toast;

import com.afollestad.easyvideoplayer.EasyVideoCallback;
import com.afollestad.easyvideoplayer.EasyVideoPlayer;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.LogUtils;
import com.thin.downloadmanager.DefaultRetryPolicy;
import com.thin.downloadmanager.DownloadRequest;
import com.thin.downloadmanager.DownloadStatusListenerV1;
import com.thin.downloadmanager.ThinDownloadManager;

import java.io.File;

/**
 * 带视频缓存的视频预览Activity
 */
public class CachedVideoViewActivity extends AppCompatActivity implements EasyVideoCallback, DownloadStatusListenerV1 {

    private static final String TAG = "CachedVideoViewActivity";

    public static final String EXTRA_VIDEO_URL = "VIDEO_URL";
    public static final String EXTRA_DEST_DIR = "DEST_DIR";
    public static final String EXTRA_AUTHORIZATION = "AUTHORIZATION";

    private EasyVideoPlayer evpPlayer;
    private ProgressDialog progressDialog;

    private String url;
    private String auth;

    private ThinDownloadManager thinDownloadManager;
    private int downloadId = -1;

    private DownloadRequest request;
    private File dir;
    private File videoFile;
    private File tempFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cached_vide_view);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        initView();
        evpPlayer.setCallback(this);
        thinDownloadManager = new ThinDownloadManager(1);
        url = getIntent().getStringExtra(EXTRA_VIDEO_URL);
        if (url == null) {
            Toast.makeText(this, "没有视频...", Toast.LENGTH_SHORT).show();
            finish();
        }
        auth = getIntent().getStringExtra(EXTRA_AUTHORIZATION);
        String dirPath = getIntent().getStringExtra(EXTRA_DEST_DIR);
        if (dirPath == null) dirPath = Environment.getDownloadCacheDirectory().getAbsolutePath();
        dir = new File(dirPath);
        FileUtils.createOrExistsDir(dir);
        videoFile = new File(dir, VideoNameGenerator.computeMD5(url));
        downloadOrPlayVideo();
    }

    private void initView() {
        evpPlayer = (EasyVideoPlayer) findViewById(R.id.evpPlayer);
    }

    @Override
    protected void onDestroy() {
        evpPlayer.stop();
        evpPlayer.release();
        if (downloadId != -1) {
            request.setStatusListener(null);
            thinDownloadManager.cancel(downloadId);
        }
        thinDownloadManager.release();
        if (progressDialog != null) {
            progressDialog.dismiss();
            progressDialog = null;
        }
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        evpPlayer.pause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (evpPlayer.isPrepared()) evpPlayer.start();
    }

    ///////////////////////////////////////////////////////////////////////////
    // DELE
    ///////////////////////////////////////////////////////////////////////////

    @Override
    public void onStarted(EasyVideoPlayer player) {

    }

    @Override
    public void onPaused(EasyVideoPlayer player) {

    }

    @Override
    public void onPreparing(EasyVideoPlayer player) {

    }

    @Override
    public void onPrepared(EasyVideoPlayer player) {

    }

    @Override
    public void onBuffering(int percent) {

    }

    @Override
    public void onError(EasyVideoPlayer player, Exception e) {
        LogUtils.i(TAG, "播放出错", "错误信息", e.getMessage());
        downloadId = -1;
        reDownloadConfirm();
    }

    @Override
    public void onCompletion(EasyVideoPlayer player) {

    }

    @Override
    public void onRetry(EasyVideoPlayer player, Uri source) {

    }

    @Override
    public void onSubmit(EasyVideoPlayer player, Uri source) {

    }

    @Override
    public void onDownloadComplete(DownloadRequest downloadRequest) {
        downloadId = -1;
        tempFile.renameTo(videoFile);
        if (progressDialog != null) {
            progressDialog.dismiss();
            progressDialog = null;
        }
        downloadOrPlayVideo();
    }

    @Override
    public void onDownloadFailed(DownloadRequest downloadRequest, int errorCode, String errorMessage) {
        LogUtils.i(TAG, "下载出错", "错误代码", errorCode, "错误信息", errorMessage);
        downloadId = -1;
        downloadRetryConfirm();
    }

    @Override
    public void onProgress(DownloadRequest downloadRequest, long totalBytes, long downloadedBytes, int progress) {
        if (progress <= 100 && progressDialog != null) {
            progressDialog.setProgress(progress);
        }
    }

    ///////////////////////////////////////////////////////////////////////////
    // CTRl
    ///////////////////////////////////////////////////////////////////////////

    private void downloadOrPlayVideo() {
        if (videoFile.exists()) {
            evpPlayer.setSource(Uri.fromFile(videoFile));
            evpPlayer.start();
        } else {
            progressDialog = new ProgressDialog(this);
            progressDialog.setMessage("下载视频中...");
            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progressDialog.setIndeterminate(false);
            progressDialog.setCancelable(true);
            progressDialog.setProgress(0);
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    if (downloadId != -1) finish();
                }
            });
            progressDialog.show();
            downloadFile();
        }
    }

    private void downloadFile() {
        tempFile = new File(dir, videoFile.getName() + VideoNameGenerator.TEMP_POSTFIX);
        if (tempFile.exists()) {
            //断点下载
//            long l = tempFile.length();
            //非断点下载
//            tempFile.delete();
        }
        Uri srcUri = Uri.parse(url);
        Uri destUri = Uri.fromFile(tempFile);
        request = new DownloadRequest(srcUri).setRetryPolicy(new DefaultRetryPolicy())
                                             .setDestinationURI(destUri)
                                             .setPriority(DownloadRequest.Priority.HIGH)
                                             .setDownloadContext(this)
                                             .setStatusListener(this);
        if (auth != null) request.addCustomHeader("Authorization", auth);
        downloadId = thinDownloadManager.add(request);
    }

    /**
     * 下载失败
     */
    private void downloadRetryConfirm() {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(CachedVideoViewActivity.this);
        builder.setTitle("提示")
               .setCancelable(false)
               .setMessage("视频下载出错, 是否尝试重新下载?")
               .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                   @Override
                   public void onClick(DialogInterface dialog, int which) {
                       finish();
                   }
               })
               .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                   @Override
                   public void onClick(DialogInterface dialog, int which) {
                       downloadOrPlayVideo();
                   }
               })
               .show();
    }

    /**
     * 重新下载
     */
    private void reDownloadConfirm() {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(CachedVideoViewActivity.this);
        builder.setTitle("提示")
               .setCancelable(false)
               .setMessage("视频播发出错, 是否尝试重新下载?")
               .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                   @Override
                   public void onClick(DialogInterface dialog, int which) {
                       finish();
                   }
               })
               .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                   @Override
                   public void onClick(DialogInterface dialog, int which) {
                       videoFile.delete();
                       tempFile.delete();
                       downloadOrPlayVideo();
                   }
               })
               .show();
    }

}
